const express = require('express')
const mailModel = require('../Model/mailModel')
const BuyModel = require('../Model/Buy')
const rootUserModel = require('../Model/rootUserModel')
const jwt = require('jsonwebtoken')
const token = require('../utils/token')
const router = express.Router()

//登录后台
router.post('/rootLogin', async (req, res, next) => {
    const { mail, password } = req.body
    const data = await rootUserModel.findOne({ mail, password })
    if (data) {
        const token = jwt.sign(
            { mail },
            'cbb',
            { expiresIn: 60 * 60 * 24 }
        )
        res.json({ code: '304', data:token, msg: '登录成功' })
    }else{
        res.json({ code: '304', msg: '账户或者密码错误' })
    }

})

//登录后台
router.post('/istoken',token, async (req, res, next) => {
    res.json({code:'200'})
})


//注册账号
router.post('/login', async (req, res, next) => {
    const { mail, password } = req.body
    const data = await mailModel.findOne({ mail, password })
    if (!data) return res.json({ code: '304', msg: '账户或者密码错误' })
    if (data.state === '封禁') return res.json({ code: '304', msg: '该账户已被封禁' })
    const token = jwt.sign(
        { mail },
        'cbb',
        { expiresIn: 60 * 60 * 24 }
    )
    res.json({ code: '200', msg: '登录成功', data: { id: data._id, token } })
})

//添加购买
router.post('/addBuy', async (req, res) => {
    const { money, integral } = req.body
    await BuyModel.create({ money, integral })
    const data = await BuyModel.find()
    res.json({ code: '200', data })
})

//获取购买
router.post('/getBuy', async (req, res) => {
    const data = await BuyModel.find()
    res.json({ code: '200', data })
})

//删除
router.post('/deleteBuy', async (req, res) => {
    const { id } = req.body
    await BuyModel.deleteOne({ _id: id })
    const data = await BuyModel.find()
    res.json({ code: '200', data })
})

module.exports = router